import { fileURLToPath } from 'url'
import fs from "fs"

export function queryAllCtrl() {
    let ctrlPath = new URL("../controller", import.meta.url).href
    // console.log(ctrlPath);

    let ctrlPath2 = fileURLToPath(ctrlPath);
    // console.log(ctrlPath2);

    let ctrlFile = fs.readdirSync(ctrlPath2)
    // console.log(ctrlFile);

    const ctrlJs = ctrlFile.filter(file => file.endsWith("Controller.js")).map(item => `${ctrlPath}/${item}`)
    // console.log(ctrlJs);

    //返回控制器文件的数组
    return ctrlJs;

}

export function registerRouter(router, ctrlJS) {
    ctrlJS.forEach(async item => {
        const { users } = await import(item)
        // console.log(users);

        users.forEach(req => {
            let reqMethod = req.method;
            // console.log(reqMethod);
            let reqUrl = req.url
            // console.log(reqUrl);
            let reqFn = req.fn
            // console.log(reqFn);

            if (reqMethod === "GET") {
                router.get(reqUrl, reqFn)
            }

            if (reqMethod === "DELETE") {
                router.delete(reqUrl, reqFn)
            }

            if (reqMethod === "POST") {
                router.post(reqUrl, reqFn)
            }

            if (reqMethod === "PUT") {
                router.put(reqUrl, reqFn)
            }

        });

    });
}